package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存
    public void save(Visitors visitors) {
        //一个访客记录，一天只保存一次
        //1、查询当天是否有访问记录
        Criteria criteria = Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate());
        boolean exists = mongoTemplate.exists(Query.query(criteria), Visitors.class);
        if(!exists) {
            //2、如果当天访问记录不存在，保存
            mongoTemplate.save(visitors);
        }
    }

    /**
     * 查询首页访客数据
     * @param userId   用户id
     * @param date     比较的保存时间
     */
    public List<Visitors> findByUserId(Long userId, Long date) {
        //构建Criteria
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("date").gte(date);
        //只查询前5条数据
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("date")))
                .limit(5);
        return mongoTemplate.find(query,Visitors.class);
    }

    //分页查询
    public List<Visitors> findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("date")))
                .skip((page-1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,Visitors.class);
    }
}
